package com.pdstudio.carrecom.ui.activity.buy;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.bean.Boutique;
import com.pdstudio.carrecom.bean.CarSelectInfo;
import com.pdstudio.carrecom.bean.City;
import com.pdstudio.carrecom.bean.ResultInfo;
import com.pdstudio.carrecom.logger.Logger;
import com.pdstudio.carrecom.tools.ImageUtil;
import com.pdstudio.carrecom.tools.JsonUtil;
import com.pdstudio.carrecom.tools.StringUtils;
import com.pdstudio.carrecom.tools.UIHelper;
import com.pdstudio.carrecom.ui.activity.ActivitySelectCommon;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.gsm.SmsMessage.SubmitPdu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 
 * 类: ActivityNewCar <br>
 * 描述: 新车购买 <br>
 * 作者: ws <br>
 * 时间: 2015-6-20 上午1:38:22
 */
public class ActivityNewCar extends Activity implements OnClickListener {

	private static final String TAG = "ActivityNewCar";

	private static final int MSG_WHAT_ABOUT = 1;

	private TextView txtTitle;
	private ImageView ivBack;

	private ResultInfo mResultInfo;

	private TextView mAboutInfo;

	private LinearLayout mLinearLayoutSelectBrand;
	private LinearLayout mLinearLayoutSelectSerial;
	private LinearLayout mLinearLayoutSelectType;

	private TextView msBrand, msSerial, msType;
	private Button mSubmit;

	private List<CarSelectInfo> mDatas = new ArrayList<>();

	private static final int TYPE_GET_BRANDS = 111111;
	private static final int TYPE_GET_SERIALS = 222222;
	private static final int TYPE_GET_TYPES = 333333;
	private int type = 111111;

	private int modelId;

	private String mCarImg = "";
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_newcar);

		initTitle();
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();

		// getAbountInfo();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Logger.i(TAG, msg);
			switch (msg.what) {
			case MSG_WHAT_ABOUT:// 关于
				if (mResultInfo != null) {
					mAboutInfo.setText(mResultInfo.data.toString());
				}
				break;
			case TYPE_GET_BRANDS: {
				// UIHelper.showSelectBrandActivity(ActivityNewCar.this,
				// mDatas);
				type = 111111;
				Intent intent = new Intent(ActivityNewCar.this,
						ActivitySelectCommon.class);
				intent.putExtra("title", "品牌选择");
				intent.putExtra("datas", (Serializable) mDatas);
				startActivityForResult(intent, type);
			}
				break;
			case TYPE_GET_SERIALS: {
				// UIHelper.showSelectSerialActivity(ActivityNewCar.this,
				// mDatas);
				type = 222222;
				Intent intent = new Intent(ActivityNewCar.this,
						ActivitySelectCommon.class);
				intent.putExtra("title", "系列选择");
				intent.putExtra("datas", (Serializable) mDatas);
				startActivityForResult(intent, type);
			}
				break;
			case TYPE_GET_TYPES: {
				// UIHelper.showSelectTypeActivity(ActivityNewCar.this, mDatas);
				type = 333333;
				Intent intent = new Intent(ActivityNewCar.this,
						ActivitySelectCommon.class);
				intent.putExtra("title", "款型选择");
				intent.putExtra("datas", (Serializable) mDatas);
				startActivityForResult(intent, type);
			}
				break;
			default:
				break;
			}
		}
	};

	private ImageView mCarImgView;

	private TextView mPrice;

	private TextView mBuyerName;
	private TextView mBuyerPhone;
	private EditText mBuyerMessage;

	private int seriesId = 0;

	/**
	 * 方法: initTitle <br>
	 * 描述: 初始化页面标题 <br>
	 * 作者: ws <br>
	 * 时间: 2015-5-24 下午5:46:11
	 */
	private void initTitle() {
		txtTitle = (TextView) findViewById(R.id.title_text_nav);

		txtTitle.setText("新车购买");

		ivBack = (ImageView) findViewById(R.id.title_back);
		ivBack.setOnClickListener(this);
	}

	private void initView() {
		mAboutInfo = (TextView) findViewById(R.id.id_about_content);
		mLinearLayoutSelectBrand = (LinearLayout) findViewById(R.id.buy_newcar);
		mLinearLayoutSelectSerial = (LinearLayout) findViewById(R.id.newcar_serial);
		mLinearLayoutSelectType = (LinearLayout) findViewById(R.id.newcar_type);
		mLinearLayoutSelectBrand.setOnClickListener(this);
		mLinearLayoutSelectSerial.setOnClickListener(this);
		mLinearLayoutSelectType.setOnClickListener(this);

		mCarImgView = (ImageView) findViewById(R.id.newcar_carimg);
		mPrice = (TextView) findViewById(R.id.newcar_price);
		mPayType = (TextView) findViewById(R.id.newcar_paytype);
		mBuyerName = (TextView) findViewById(R.id.newcar_name);
		mBuyerPhone = (TextView) findViewById(R.id.newcar_phone);
		mBuyerMessage = (EditText) findViewById(R.id.more_sug5);

		msBrand = (TextView) findViewById(R.id.exchange_brand);
		msSerial = (TextView) findViewById(R.id.exchange_serial);
		msType = (TextView) findViewById(R.id.exchange_type);

		mSubmit = (Button) findViewById(R.id.newbuy_submit);
		mSubmit.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;
		case R.id.buy_newcar: {
			type = TYPE_GET_BRANDS;
			getDatas(ServiceHelper.XZPP);
		}
			break;
		case R.id.newcar_serial: {
			type = TYPE_GET_SERIALS;
			getDatas(ServiceHelper.XZXL);
		}
			break;
		case R.id.newcar_type: {
			type = TYPE_GET_TYPES;
			getDatas(ServiceHelper.XZKX);
			break;
		}
		case R.id.newbuy_submit:
			submit();
			break;
		}
	}

	private void submit() {
		try {
			HttpExecuteJson http = new HttpExecuteJson(this,
					mBuyOrderListener);
			RequestParams rps = new RequestParams();
			rps.addBodyParameter("uid", AppContext.getInstance().getUserId()
					+ "");
			rps.addBodyParameter("os", "android");
			rps.addBodyParameter("content",
					StringUtils.utf8Encode(mBuyerMessage.getText().toString()));
			rps.addBodyParameter("model_id", modelId + "");
			rps.addBodyParameter("type", "0");
			rps.addBodyParameter("name",
					StringUtils.utf8Encode(mBuyerName.getText().toString()));
			rps.addBodyParameter("tel",
					StringUtils.utf8Encode(mBuyerPhone.getText().toString()));
			// TODO:获取全款或者贷款
			rps.addBodyParameter("payment", "0");
			http.post(ServiceHelper.TJYY, rps);
		} catch (Exception e) {
		}

	}

	private void getDatas(String url) {
		try {
			HttpExecuteJson http = new HttpExecuteJson(this,
					mNewCarBoutiqueListener);
			Map<String, Object> rps = new HashMap<String, Object>();
			rps.put("os", "android");
			rps.put("size", "30-60");

			rps.put("uid", AppContext.getInstance().getUserId());
			rps.put("brandId", brandId);
			rps.put("seriesId", seriesId );
			Logger.i(url);
			http.get(url, rps);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private httpReturnJson mNewCarBoutiqueListener = new httpReturnJson() {

		@Override
		public void onSuccess(String result) {
			Logger.json(result);
			ResultInfo resultInfo = null;
			try {
				resultInfo = new Gson().fromJson(result,
						new TypeToken<ResultInfo>() {
						}.getType());
				if ((resultInfo != null)
						&& (resultInfo.msg
								.equals(ServiceHelper.msg_code_sucess))) {
					try {
						mResultInfo = resultInfo;
						Logger.i("天气", resultInfo);

						mDatas = JsonUtil.fromJsonArray(
								JsonUtil.toJson(mResultInfo.data),
								CarSelectInfo.class);
						Message msg = new Message();
						msg.obj = mDatas;
						msg.what = type;
						mHandler.sendMessage(msg);

					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int error, String msg) {

		}

		@Override
		public void onCancel() {

		}
	};

	private TextView mPayType;

	private int brandId = 0;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case TYPE_GET_BRANDS: {

			brandId = ((CarSelectInfo) data.getExtras().get("select")).id;
			msBrand.setText(((CarSelectInfo) data.getExtras().get("select")).name);
		}
			break;
		case TYPE_GET_SERIALS: {
			seriesId = ((CarSelectInfo) data.getExtras().get("select")).id;
			msSerial.setText(((CarSelectInfo) data.getExtras().get("select")).name);
		}
			break;
		case TYPE_GET_TYPES: {
			msType.setText(((CarSelectInfo) data.getExtras().get("select")).name);
			mCarImg = ((CarSelectInfo) data.getExtras().get("select")).url;
			mPrice.setText(((CarSelectInfo) data.getExtras().get("select")).price);
			mPayType.setText(((CarSelectInfo) data.getExtras().get("select")).name);
			modelId = ((CarSelectInfo) data.getExtras().get("select")).id;

			ImageUtil.DisplayImage(mCarImg, mCarImgView);
		}
			break;
		}

	}
	
	private httpReturnJson mBuyOrderListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(ActivityNewCar.this, "预约失败！" + msg);
		}

		@Override
		public void onCancel() {
			UIHelper.ToastMessage(ActivityNewCar.this, "预约失败！");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			DoJsonSub(result);
		}
	};
	
	/*
	 * 提交预约
	 */
	private void DoJsonSub(String json) {
		ResultInfo edv = null;
		try {
			edv = new Gson().fromJson(json, new TypeToken<ResultInfo>() {
			}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				UIHelper.ToastMessage(ActivityNewCar.this, "预约成功！");
				finish();
			} else {
				UIHelper.ToastMessage(ActivityNewCar.this, "预约失败！"+edv.msg);

			}
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(ActivityNewCar.this, "预约失败！"+e.getMessage());
		}
	}

}
